package work.com;

import java.util.Scanner;

public class Exam04 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入字符串：");
        String str = sc.next();
        boolean isValid = isValid2(str);
        if (isValid){
            System.out.println(str + "是有效字符串");
        }else {
            System.out.println(str + "不是有效字符串");
        }

    }

    public static boolean isValidParentheses(String s) {
        int leftCount = 0;
        int rightCount = 0; 
        for (char c : s.toCharArray()) {
            if (c == '(') {
                leftCount++;
            } else if (c == ')') {
                rightCount++;
            }
            if (rightCount > leftCount || rightCount < leftCount) {
                return false;
            }
        }
        return true;
    }
    public static boolean isValid2(String str) {
        // 匹配正确的一对 替换成空字符串
        if (str == null) {
            return false;
        }
        if (str.isBlank() || str.isEmpty()) {
            return true;
        }
        str = str.replace(" ", "");
        while (str.contains("()")) {
            str = str.replaceAll("\\(\\)", "");
        }
        return str.isEmpty() || str.isBlank();
    }

    public static boolean isValid3(String str) { // (((()))
        // 栈 先进后出
        char[] chars = new char[str.length()]; // ( ( '('
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c == '(') {
                chars[count++] = c;
            } else if (c == ')') {
                if (count == 0) {
                    return false;
                }
                if (chars[count - 1] == '(') {
                    chars[--count] =' ';
                }
            }
        }
        return count == 0;
    }
}
